﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Xml;
using iReaper.IndexService.Common;
using iReaper.IndexService.Common.TaskEngine;

namespace iReaper.IndexService.MSEvents
{
    public class DataCollectorTask : TaskBase
    {
        const string SEARCH_URL = "https://msevents.microsoft.com/cui/Handlers/DataCollector.ashx";
        const string SEARCH_PARM_BASE = "culture={0}&eventType=3&searchcontrol=no&s=1&pageNumber={1}";
        HashSet<string> eventTbl = new HashSet<string>();
        #region ITask Members

        #region private methods
        private void QueryEvents(out EventItem[] events, out int pageCount,string culture, int pageNum)
        {
            string search_param = string.Format(SEARCH_PARM_BASE,culture, pageNum);
            WebClient client = new WebClient();
            client.Encoding = System.Text.Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            var result = client.UploadValues(SEARCH_URL, "POST", System.Web.HttpUtility.ParseQueryString(search_param));
            System.IO.MemoryStream strm = new System.IO.MemoryStream(result);
            System.IO.StreamReader reader = new System.IO.StreamReader(strm, System.Text.Encoding.UTF8,true);
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(reader);
            // Check page count
            var strPageCount = xmldoc.SelectSingleNode("/root").Attributes["pageCount"].Value;
            pageCount = int.Parse(strPageCount);
            events = ParseResultXml(xmldoc, culture);
            strm.Close();
        }

        private EventItem[] ParseResultXml(XmlDocument xmldoc, string culture)
        {
            var nodes = xmldoc.DocumentElement.SelectNodes("//eventData");
            List<EventItem> items = new List<EventItem>();
            for (int i = 0; i < nodes.Count; i++)
            {
                var item = ParseOneNode(nodes[i]);
                item.Language = culture;
                if (!eventTbl.Contains(item.EventID))
                {
                    eventTbl.Add(item.EventID);
                    items.Add(item);
                }
            }

            return items.ToArray();
        }
    //    <title>Microsoft Office System Webcast: Advanced Tips and Tricks for Getting Data and Other Content into and out of Your Documents (Level 300)</title>
    //<categoryId>3</categoryId>
    //<eventId>1032369392</eventId>
    //<description>
    //  Do you often find yourself retyping or copying data and other content throughout a document or between documents or programs? If so, stop typing and join this webcast for a look at tools across the 2007 Microsoft Office system that manage information for you and enable you to do more with your documents than you might imagine. In this session, take a look at new or improved options for repeating content throughout a document, reusing slides in other presentations, importing and analyzing data, changing content and formatting without even opening documents, creating diagrams from data, and sharing information with others. If you ever feel as though you spend too much time on tasks in Microsoft Office  programs, or wonder if there are faster and easier ways to get your work done and create better content, this webcast is for you.Presenters: Stephanie Krieger, Microsoft Press Author and Office System MVP, Arouet.netStephanie Krieger is a Microsoft Office Most Valuable Professional (MVP) and author of two books, Advanced Microsoft Office Documents 2007 Edition Inside Out and Microsoft Office Document Designer (Microsoft Press, 2007 and 2004, respectively). She has helped many global companies develop enterprise solutions for the Microsoft Office System and taught numerous professionals how to build great documents by understanding how Microsoft Office programs "think." Stephanie writes for several Microsoft Web pages and frequently delivers Microsoft Office webcasts. Visit her blog, arouet.net, for a regularly updated collection of tips. If you have questions or feedback, contact us.
    //</description>
    //<startdate>2/11/2008 12:00 AM  Pacific Time (US &amp; Canada)</startdate>
    //<enddate>- 2/7/2012 11:59 PM</enddate>
    //<detailUrl>https://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032369392&amp;culture=en-US</detailUrl>
    //<duration> | Duration:60 Minutes</duration>
    //<primaryLanguage>English</primaryLanguage>
    //<targetAudience>Additional Information Worker</targetAudience>
    //<starRatingImage>resources/images/5Star.jpg</starRatingImage>
    //<starRatingVisibility>true</starRatingVisibility>
    //<userbookmarked>false</userbookmarked>
    //<userregistered>false</userregistered>
    //<quickactionimg>register</quickactionimg>
    //<quickactionurl>https://msevents.microsoft.com/cui/Register.aspx?EventID=1032369392&amp;culture=en-US&amp;countryCode=US</quickactionurl>
    //<quickaction>1</quickaction>
        private EventItem ParseOneNode(XmlNode xmlNode)
        {
            EventItem item = new EventItem();
            item.Title = GetInnerText(xmlNode, "./title");
            item.EventID =GetInnerText(xmlNode, "./eventId");
            item.Description =GetInnerText(xmlNode, "./description").Trim();
            item.StartDataString =GetInnerText(xmlNode, "./startdate");
            item.TargetAudience = GetInnerText(xmlNode, "./targetAudience");
            DateTime dt;
            if (item.StartDataString.Contains(" Pacific Time (US & Canada)"))
            {
                item.StartDataString = item.StartDataString.Replace(" Pacific Time (US & Canada)", "").Trim();
            }
            else if (item.StartDataString.Contains(" 中国"))
            {
                item.StartDataString = item.StartDataString.Replace(" 中国", "");
            }
            if (DateTime.TryParse(item.StartDataString, out dt))
            {
                item.StartData = dt;
            }
            item.DetailUrl = GetInnerText(xmlNode, "./detailUrl");
            item.QuickActionUrl =GetInnerText(xmlNode,"./quickactionurl");
            int quickId;
            if (int.TryParse(GetInnerText(xmlNode, "./quickaction"), out quickId))
            {
                item.QuickActionId = quickId;
            }
            // Get ratio
            string ratioString = GetInnerText(xmlNode, "./starRatingImage");
            if (!string.IsNullOrEmpty(ratioString) && ratioString.StartsWith("resources/images/"))
            {
                var jpgName = ratioString.Substring("resources/images/".Length);
                var strRatio = jpgName.Substring(0, jpgName.Length - "Star.jpg".Length).Replace("-", ".");
                float ratio;
                if (float.TryParse(strRatio, out ratio))
                {
                    item.Ratio = ratio;
                }
            }

            return item;
        }

        private string GetInnerText(XmlNode node, string xpath)
        {
            var targetNode = node.SelectSingleNode(xpath);
            return targetNode == null ? string.Empty : targetNode.InnerText;
        }

        #endregion

        #endregion

        public override void Start()
        {
            EventItem item = null;
            while((item = GetItem()) != null)
            {
                eventTbl.Add(item.EventID);
            }
 
            System.Threading.ThreadStart entry = PrivateProcessEntry;
            entry.BeginInvoke(null, null);
        }

        private void PrivateProcessEntry()
        {
            EventItem[] buffer = null;
            int pageCount = 0;
            string[] cultures = new string[] { "en-us", "zh-cn" };
            foreach (var culture in cultures)
            {
                // First time invoke, get data and parameters
                QueryEvents(out buffer, out pageCount, culture, 1);
                SetResult(buffer);
                System.Threading.ThreadPool.SetMaxThreads(10, 20);
                int count = pageCount - 1;
                System.Threading.ManualResetEvent waitHandle = new System.Threading.ManualResetEvent(false);
                for (int i = 2; i <= pageCount; i++)
                {
                    System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(delegate(object index)
                    {
                        EventItem[] localBuffer = null;
                        int localPageCount = 0;
                        QueryEvents(out localBuffer, out localPageCount, culture, (int)index);
                        SetResult(localBuffer);
                        int left = System.Threading.Interlocked.Decrement(ref count);
                        if (left == 0)
                        {
                            waitHandle.Set();
                        }
                    }), i);
                }
                waitHandle.WaitOne();
            }

            Done();
        }
    }
}
